from datetime import datetime
from apps.common.utils.response import response_message, response_success, response_action
from decimal import Decimal
import random
import json
from apps.common.utils.tools import random_num

from apps.pay.order.countAward.countPersonalAward import countPersonalAwardHandle
from apps.pay.order.countAward.countFranchiseeAward import countFranchiseeAward
from apps.pay.order.countAward.countProfit import countProfitFun
from apps.pay.order.dao import OrderDao
from apps.system.rank.dao import RankDao
from apps.merchant.sku.dao import SkuDao
from apps.merchant.item.dao import ItemDao
from apps.merchant.sku.dao import SkuDao
from apps.user.dao import UserDao

from apps.pay.order.payReturnHandle.upRank import upRankHandle
from apps.pay.order.payReturnHandle.buyItem import buyItemHandle
from apps.common.ali.sendSms.service import sendSmsForAli
from apps.chat.message.service import sendMessage
from apps.pay.order.payReturnHandle.incomesDeductionActivity import incomesDeductionActivityHandle
from apps.pay.order.payReturnHandle.expenseSendIncomesActivity import expenseSendIncomesActivityHandle
from apps.pay.order.payReturnHandle.dismantleOrderByItem import dismantleOrderByItemHandle
from apps.user.countVerticalData import updateVerticalPerformance
from apps.user.countTeamDate import updateTeamPerformance
from apps.user.countSelfData import updateSelfPerformance
from apps.chat.message.functions import MessageFun
from apps.pay.order.countAward.countTeamAward import countTeamAwardFun
from apps.pay.order.countAward.countTeamLevel import countTeamLevelFun
from apps.pay.recordIncomes.dao import RecordIncomesDao
from apps.merchant.shop.dao import ShopDao
from apps.system.lessee.dao import LesseeDao

# 设置实际支付价格
def setPayMoney(params, data, user):
    # print('设置实际支付金额', data.get('scene'), params.get('orderItemList'))
    if data.get('scene') == 'generay' or data.get('scene') == 'giftSection':
        costPrice = 0
        sellingPrice = 0
        realPay = 0
        realPayIncomes = 0
        discountParams = []
        for orderItem in params.get('orderItemList'):
            if orderItem.get('sku'):
                sku = SkuDao().findOneByObjId(orderItem.get('sku'))
                if sku:
                    costPrice = costPrice + sku.costPrice * orderItem.get('payCount')
                    sellingPrice = sellingPrice + sku.sellingPrice * orderItem.get('payCount')
        # 计算优惠
        try:
            if user:
                if user.incomesCredit > 0:
                    if user.incomesCredit < sellingPrice * Decimal(0.1):
                        realPay = sellingPrice - user.incomesCredit
                        discountParams.append({'type': '抵扣积分', 'money': str(user.incomesCredit)})
                    else:
                        realPay = Decimal(sellingPrice * Decimal(0.9)).quantize(Decimal("0.00"))
                        discountParams.append({'type': '抵扣积分', 'money': str(Decimal(sellingPrice-realPay))})
                else:
                    realPay = sellingPrice
        except Exception as e:
            realPay = realPay
        return {'status': 200, 'data': {
            'costPrice': str(Decimal(costPrice).quantize(Decimal("0.00"))),
            'sellingPrice': str(Decimal(sellingPrice).quantize(Decimal("0.00"))),
            'realPay': str(Decimal(realPay).quantize(Decimal("0.00"))),
            'realPayIncomes': str(Decimal(realPayIncomes).quantize(Decimal("0.00"))),
            'discountParams': discountParams
            }}
    elif data.get('scene') == 'recharge':
        sellingPrice = params.get('realPay')
        realPay = params.get('realPay')
        realPayIncomes = 0
        discountParams = []
        return {'status': 200, 'data': {
            'sellingPrice': str(Decimal(sellingPrice).quantize(Decimal("0.00"))),
            'realPay': str(Decimal(realPay).quantize(Decimal("0.00"))),
            'realPayIncomes': str(Decimal(realPayIncomes).quantize(Decimal("0.00"))),
            'discountParams': discountParams
            }}
    elif data.get('scene') == 'payForFranchisee':
        sellingPrice = params.get('realPay')
        realPay = params.get('realPay')
        realPayIncomes = 0
        discountParams = []
        return {'status': 200, 'data': {
            'sellingPrice': str(Decimal(sellingPrice).quantize(Decimal("0.00"))),
            'realPay': str(Decimal(realPay).quantize(Decimal("0.00"))),
            'realPayIncomes': str(Decimal(realPayIncomes).quantize(Decimal("0.00"))),
            'discountParams': discountParams
            }}
    else:
        print('支付场景不存在')
        return {'status': 500, 'data': response_message('支付场景不存在')}

# 随机立减
def random_sub(money, m, n):
    _random = random.uniform(m, n)
    if money > Decimal(_random):
        money = money - Decimal(_random)
    return money.quantize(Decimal("0.00"))



# 创建订单之前校验
def beforeCreateOrderScene(params, data, user):
    print('创建订单之前校验', params)
    if data.get('scene') == 'generay' or data.get('scene') == 'giftSection':
        # print('校验库存', params.get('orderItemList'))
        orderItemList = params.get('orderItemList')
        for orderItem in orderItemList:
            # 检验是否上架
            item = ItemDao().findOneByObjId(orderItem.get('item'))
            if item.status == 0:
                return {'status': 500, 'data': response_message('商品' + item.name + '暂未上架')}
            if orderItem.get('sku') and item.isCheckStock:
                # 校验sku库存
                sku = SkuDao().findOneByObjId(orderItem.get('sku'))
                if sku.stock < orderItem.get('payCount'):
                    return {'status': 500, 'data': response_message('库存不足')}
    elif data.get('scene') == 'recharge':
        return {'status': 200, 'data': {}}
    elif data.get('scene') == 'payForFranchisee':
        return {'status': 200, 'data': {}}
    else:
        return {'status': 500, 'data': response_message('支付场景不存在')}
    return {'status': 200, 'data': {}}

# 创建订单
def createOrderScene(params, data, user):
    if data.get('scene') == 'generay' or data.get('scene') == 'giftSection':
        if data.get('scene') == 'generay':
            orderItemList = params.get('orderItemList')
            for orderItem in orderItemList:
                # 计算利润
                sku = SkuDao().findOneByObjId(orderItem.get('sku'))
                if sku.item.activity:
                    res = countProfitFun({'sellingPrice': sku.sellingPrice, 'costPrice': sku.costPrice, 'activityId': sku.item.activity.id, 'scene': 'generay', 'payCount': orderItem.get('payCount')})
                    orderItem.update(res)
            data['content'] = json.dumps({'orderItemList': orderItemList})
        if data.get('scene') == 'giftSection':
             # 计算利润
            orderItemList = params.get('orderItemList')
            for orderItem in orderItemList:
                # 计算利润
                sku = SkuDao().findOneByObjId(orderItem.get('sku'))
                if sku.item.activity:
                    res = countProfitFun({'sellingPrice': sku.sellingPrice, 'costPrice': sku.costPrice, 'activityId': sku.item.activity.id, 'scene': 'giftSection'})
                    orderItem.update(res)
            data['content'] = json.dumps({'orderItemList': orderItemList})

        _order = OrderDao().create(data)
        # 创建订单成功之后，减少库存
        content = json.loads(_order.content)
        for orderItem in content.get('orderItemList'):
            item = ItemDao().findOneByObjId(orderItem.get('item'))
            # 减少库存
            if orderItem.get('sku'):
                if orderItem.get('sku') and item.isCheckStock:
                    SkuDao().subStock(orderItem.get('sku'), orderItem.get('payCount'))
        return {'status': 200, 'data': response_success({'orderId': _order.orderId})}
    elif data.get('scene') == 'recharge':
        content = {'orderItemList': []}
        data['content'] = json.dumps(content)
        _order = OrderDao().create(data)
        return {'status': 200, 'data': response_success({'orderId': _order.orderId})}
    elif data.get('scene') == 'payForFranchisee':
        shop = ShopDao().findOneByObjId(params.get('shopId'))
        lessee = LesseeDao().getLessee()
        content = {'orderItemList': []}
        content['shopUserId'] = shop.user.id
        content['shopParentId'] = shop.user.parent.id if shop.user.parent else ''
        content['discountsRate'] = str(shop.discountsRate)
        content['franchiseeParams'] = lessee.franchiseeParams
        data['content'] = json.dumps(content)
        _order = OrderDao().create(data)
        return {'status': 200, 'data': response_success({'orderId': _order.orderId})}
    else:
        return response_message('支付场景不存在')


# 支付成功返回
def payReturnScene(payway, orderId, transactionId):
    _order = OrderDao().findOneByOrderId(orderId)
    if _order.scene == 'generay' or _order.scene == 'giftSection':
        if _order.orderStatus == 'WAIT_PAY':
            print('商品购买处理')
            data = {}
            data['orderStatus'] = 'WAIT_SEND'
            data['payTime'] = datetime.now()
            data['payway'] = payway
            data['transactionId'] = transactionId
            # 机器人订单直接完成
            if _order.user.isRobot:
                data['orderStatus'] = 'FINISH'
            _order = OrderDao().update(_order.id, data)
            # 扣除用户抵扣积分
            subIncomesCredit(_order)
            # 统计自己的业绩
            updateSelfPerformance('add', _order.user, 1, _order.sellingPrice)
            # 给用户升级
            _user = UserDao().findOneByObjId(_order.user.id)
            if _user.selfPerformance >= 100:
                UserDao().addRank(_order.user, 1)
            # 检查上级级别
            UserDao().checkParentRank(_order.user)
            # 发放个人奖励
            sendContributionValues = countPersonalAwardHandle(_order)
            # 发放团队奖励
            countTeamAwardFun(_order, sendContributionValues)
            # 计算团队级别
            countTeamLevelFun(_order)
            # 给用户发送订单信息
            if _order.addrinfo:
                addrinfoDict = json.loads(_order.addrinfo)
                MessageFun().sendMessage(None, _order.user, 'jytz', {'title': '订单通知', 'content': '您已支付成功，收货地址为'+addrinfoDict.get('addrInfo')})
            # 处理购买商品后销量库存等信息
            buyItemHandle(_order)
            # 根据商品拆单
            dismantleOrderByItemHandle(_order)

    elif _order.scene == 'recharge':
        if _order.orderStatus == 'WAIT_PAY':
            print('充值处理')
            data = {}
            data['orderStatus'] = 'FINISH'
            data['payTime'] = datetime.now()
            data['payway'] = payway
            data['transactionId'] = transactionId
            _order = OrderDao().update(_order.id, data)
            # 增加购物积分
            money = _order.sellingPrice
            payway = 'incomes'
            UserDao().addWallet(payway, _order.user, money)
            data = {}
            data['scene'] = 'inMoney'
            data['user'] = _order.user.id
            data['fromUser'] = _order.user.id
            data['orderId'] = _order.orderId
            data['money'] = money
            data['payway'] = payway
            data['changeWay'] = 'add'
            data['orderStatus'] = 'FINISH'
            RecordIncomesDao().create(data)
    elif _order.scene == 'payForFranchisee':
        if _order.orderStatus == 'WAIT_PAY':
            print('加盟商收款处理')
            data = {}
            data['orderStatus'] = 'FINISH'
            data['payTime'] = datetime.now()
            data['payway'] = payway
            data['transactionId'] = transactionId
            _order = OrderDao().update(_order.id, data)
            # 统计自己的业绩
            updateSelfPerformance('add', _order.user, 1, _order.sellingPrice)
            # 给用户升级
            _user = UserDao().findOneByObjId(_order.user.id)
            if _user.selfPerformance >= 100:
                UserDao().addRank(_order.user, 1)
            # 检查上级级别
            UserDao().checkParentRank(_order.user)
            # 发放加盟店分红
            sendContributionValues = countFranchiseeAward(_order)
            # 发放团队奖励
            countTeamAwardFun(_order, sendContributionValues)
            # 计算团队级别
            countTeamLevelFun(_order)
            # 给用户发送订单信息
            if _order.addrinfo:
                addrinfoDict = json.loads(_order.addrinfo)
                MessageFun().sendMessage(None, _order.user, 'jytz', {'title': '订单通知', 'content': '您已支付成功，收货地址为'+addrinfoDict.get('addrInfo')})
            # 处理购买商品后销量库存等信息
            buyItemHandle(_order)


# 取消订单返回
def cancelOrderReturnScene(orderId):
    order = OrderDao().findOneByOrderId(orderId)
    # 返还库存 和 扣除销量
    content = json.loads(order.content)
    if order.scene == 'generay' or order.scene == 'goldCustom':
        for item in content.get('orderItemList'):
            if item.get('sku'):
                ItemDao().subSales(item.get('item'), item.get('payCount'))
                SkuDao().addStock(item.get('sku'), item.get('payCount'))
                SkuDao().subSales(item.get('sku'), item.get('payCount'))
    elif order.scene == 'guest':
        return


# 扣除用户抵扣积分
def subIncomesCredit(order):
    user = UserDao().findOneByObjId(order.user.id)
    if user.incomesCredit > 0:
        money = 0
        if user.incomesCredit <= order.sellingPrice * Decimal(0.1):
            money = user.incomesCredit
            user.incomesCredit = 0
            user.save()
        else:
            user.incomesCredit = user.incomesCredit - order.sellingPrice * Decimal(0.1)
            money = order.sellingPrice * Decimal(0.1)
            user.save()

        # 扣除用户抵扣积分
        data = {}
        data['scene'] =  'expense'
        data['user'] = user.id
        data['fromUser'] = order.user.id
        data['orderId'] = order.orderId
        data['money'] = Decimal(money).quantize(Decimal('0.00'))
        data['payway'] = 'incomesCredit'
        data['changeWay'] = 'sub'
        RecordIncomesDao().create(data)